package com.yya.ratelimiter.factory;

import com.yya.ratelimiter.service.CounterWindow;
import com.yya.ratelimiter.service.LimitationAlgorithm;
import com.yya.ratelimiter.service.SlidingWindow;
import com.yya.ratelimiter.service.TokenBucket;
import com.yya.ratelimiter.enums.LimitationAlgorithmType;
import com.yya.ratelimiter.utils.SpringContextUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.NoSuchElementException;

/**
 * @Autor: yuanyongan
 * @Description:
 * @Date 2023/1/12 13:01
 */

@Component
public class AlgorithmFactory {
    private static final HashMap<LimitationAlgorithmType, LimitationAlgorithm> algorithmMap = new HashMap<>();

    /**
     * 因为CounterWindow中包含对象注入，所以不能用new CounterWindow的方法去实例化
     * 不然的话redis的类注入不了
     * @param type
     * @return
     */
    public LimitationAlgorithm getAlgorithm(LimitationAlgorithmType type){
        switch (type){
            case TokenBucketAlg:
                return SpringContextUtils.getBean(TokenBucket.class);
            case CounterWindowAlg:
                return SpringContextUtils.getBean(CounterWindow.class);
            case SlidingWindowAlg:
                return SpringContextUtils.getBean(SlidingWindow.class);
            default:
                throw new NoSuchElementException("暂不支持该算法");
        }
    }
}
